﻿using BlazorServerCRUD.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Components;

namespace BlazorServerCRUD.Pages;
partial class Index
{
    [Inject]ApplicationDbContext Context { get; set; }

    IEnumerable<User> Users { get; set; } = Enumerable.Empty<User>();

    bool IsLoading { get; set; }


    User Model { get; set; } = new();

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await GetListAsync();
        }
    }

    async Task GetListAsync()
    {
        IsLoading = true;
        StateHasChanged();
        await Task.Delay(1000);

        Users = await Context.Users.ToListAsync();

        IsLoading = false;
        StateHasChanged();
    }


    bool IsShowingForm { get; set; }
    bool IsEdit { get; set; }

    void ShowForm()
    {
        IsShowingForm = true;
        StateHasChanged();
    }
    void HideForm()
    {
        IsShowingForm = false; 
        StateHasChanged();
    }

    async Task SubmitAsync()
    {
        if (IsEdit && SelectedId >-1)
        {
            var user = await Context.Users.FindAsync(SelectedId);
            Model.Name = user.Name;
            Model.Email = user.Email;
            await Context.SaveChangesAsync();
        }
        else
        {
            Context.Users.Add(Model);
            await Context.SaveChangesAsync();
        }
        await GetListAsync();

        Model = new();
        HideForm();
    }

    int SelectedId { get; set; }

    void SelectItem(int id)
    {
        SelectedId = id;
    }

    async void Edit(int id)
    {
        SelectItem(id);
        IsEdit = true;

        Model = await Context.Users.FindAsync(id);

        ShowForm();
    }

    async Task Delete(int id)
    {
        var user= await Context.Users.FindAsync(id);
        Context.Remove(user);
        await Context.SaveChangesAsync();

        await GetListAsync();
    }
}
